package com.david.concurrent.notify.wait;

import java.util.concurrent.BlockingQueue;

/**
 * @author wade
 * @version 1.0
 * @date 2021/7/19 16:20
 */
public class Consumer implements Runnable{

    private BlockingQueue<String> queue;

    public Consumer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true){
            synchronized (queue){
                while (queue.size()==0){
                    try {
                        queue.wait();
                        System.out.println("队列为空，消费者等待");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    //消费元素，并通知唤醒生产者线程
                    String take = queue.take();
                    System.out.println(Thread.currentThread().getName()+"消费： " + take);
                    queue.notifyAll();
                    Thread.sleep(500L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
